package cn.hx.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfigurer {

    @Autowired
    private OncePerRequestFilter authenticationTokenFilter;

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)// 指定session的创建策略，不使用session
                .and()// 再次获取到HttpSecurity对象
                .authorizeRequests().antMatchers("/login").anonymous()// 对于登录接口，允许匿名访问
                .anyRequest().authenticated()// 进行认证请求的配置
                .and().addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);//指定认证令牌过滤器
        return http.build();
    }

    @Bean
   public AuthenticationManager authenticationManager() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);//使用UserDetailsService完成数据库查询和设置角色与权限工作
        daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());//使用的密码加密算法
        ProviderManager providerManager = new ProviderManager(daoAuthenticationProvider);
        return providerManager;
    }


}
